﻿using System;
using System.Collections.Generic;
using System.Text;
using Microsoft.AspNetCore.Http;
using Newtonsoft.Json;

// 参考 https://www.meiwen.com.cn/subject/uprjattx.html
namespace BoYuanCore.Framework.CoreMvc
{
    /*
        //可能需要设置cookie
         services.AddAuthentication().AddCookie();
            services.AddControllersWithViews();

    // session 设置
    services.AddSession(options =>
    {
    // 设置 Session 过期时间
    options.IdleTimeout = TimeSpan.FromDays(90);
    options.Cookie.HttpOnly = true;
    });
    */

    /// <summary>
    /// session存字符串(ConfigureServices需要services.AddSession(); Configure需要 app.UseSession();)
    /// </summary>
    public static class SimpleSession
    {
        /// <summary>
        /// 设置session
        /// </summary>
        /// <param name="session"></param>
        /// <param name="key"></param>
        /// <param name="valueStr"></param>
        public static void SetString(this ISession session,string key,string valueStr)
        {
            session.Set(key, Encoding.Default.GetBytes(valueStr)); 
        }

        /// <summary>
        /// 获取session
        /// </summary>
        /// <param name="session"></param>
        /// <param name="key"></param>
        /// <returns></returns>
        public static string GetString(this ISession session, string key)
        {
            return session.TryGetValue(key, out var valueStr) ? Encoding.Default.GetString(valueStr) : null;
        }

        /// <summary>
        /// 对象存入session 
        /// </summary>
        /// <param name="session"></param>
        /// <param name="key"></param>
        /// <param name="valueObj"></param>
        public static void SetObject(this ISession session, string key, object valueObj)
        {
            if (valueObj==null) return;

            string json = JsonConvert.SerializeObject(valueObj);
            session.SetString(key,json);
        }

        public static T GetObject<T>(this ISession session, string key)
        {
            string json=  session.GetString(key);
            if (json == null) return default(T);
            return JsonConvert.DeserializeObject<T>(json);
        }
    }

    
}
